package com.spark.quartz.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spark.quartz.entity.QrtzJob;
import com.spark.quartz.mapper.QrtzJobMapper;
import org.quartz.*;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * 任务调度服务
 *
 * @author LYCHEE
 * @date 2025/4/3 10:29
 */
@Service
public class JobScheduleManager {

    @Resource
    private Scheduler scheduler;

    @Resource
    private QrtzJobMapper jobMapper;

    /**
     * 初始化任务调度
     */
    @PostConstruct
    public void init() throws SchedulerException {
        List<QrtzJob> jobList = jobMapper.selectList(new QueryWrapper<QrtzJob>().eq("status", 0));
        for (QrtzJob job : jobList) {
            scheduleJob(job);
        }
    }

    /**
     * 创建或更新任务
     */
    public void scheduleJob(QrtzJob job) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(job.getJobName());
        if (scheduler.checkExists(jobKey)) {
            scheduler.deleteJob(jobKey);
        }

        // 构建JobDetail
        JobDataMap dataMap = new JobDataMap();
        dataMap.put("JOB_DATA", job);
        JobDetail jobDetail = JobBuilder.newJob(QuartzJobExecute.class)
                .withIdentity(jobKey)
                .usingJobData(dataMap)
                .build();

        // 配置Trigger策略
        Trigger trigger = buildTrigger(job);
        scheduler.scheduleJob(jobDetail, trigger);

        // 如果任务状态为暂停，立即暂停
        if (1 == job.getStatus()) {
            scheduler.pauseJob(jobKey);
        }
    }

    /**
     * 删除任务
     * @param jobId 任务ID
     */
    public void deleteJob(String jobId) throws SchedulerException {
        // 1. 查询任务信息
        QrtzJob job = jobMapper.selectById(jobId);
        if (job == null) {
            throw new RuntimeException("任务不存在");
        }

        // 2. 构造 JobKey
        JobKey jobKey = JobKey.jobKey(job.getJobName());

        // 3. 从调度器中删除任务
        if (scheduler.checkExists(jobKey)) {
            // 删除任务及其关联的 Trigger
            scheduler.deleteJob(jobKey);
        }
    }

    /**
     * 构建Trigger（支持misfire策略）
     */
    private Trigger buildTrigger(QrtzJob job) {
        CronScheduleBuilder cronBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());

        // 设置misfire策略
        switch (job.getMisfirePolicy()) {
            case 0:
                // 立即执行
                cronBuilder.withMisfireHandlingInstructionFireAndProceed();
                break;
            case 1:
                // 执行一次
                cronBuilder.withMisfireHandlingInstructionDoNothing();
                break;
            default:
                // 默认策略：放弃执行（避免误用 IgnoreMisfires）
                cronBuilder.withMisfireHandlingInstructionDoNothing();
        }

        return TriggerBuilder.newTrigger()
                .withIdentity(job.getJobName() + "_Trigger")
                .withSchedule(cronBuilder)
                .build();
    }


}
